/**
 * 
 */
package systole.processor;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Iterator;
import systole.domain.signals.FinalSignal;

import systole.domain.signals.Segment;
import systole.domain.signals.SelectedSegment;
import systole.math.Derivative;
import systole.math.MathUtils;

/**
 * @author juan
 * 
 */
public class SignalProcessor {

//    /**
//     *
//     * @param signal the signal.
//     * @param currentPos the current position on final signal generation.
//     * @return if there are more points to add.
//     */
//    private Boolean next(Collection<SelectedSegment> segments, int currentPos) {
//        Iterator<SelectedSegment> itSegments = segments.iterator();
//        Boolean next = false;
//        while ((itSegments.hasNext()) & (!next)) {
//            SelectedSegment current = itSegments.next();
//            next = current.getSegment().size() > currentPos;
//        }
//        return next;
//    }

    /**
     *
     * @param segments list of segment selected
     * @return the final segment
     */
    public Segment process(Collection<SelectedSegment> segments) {
        Segment finalSegment = new Segment();
        int amountOfSements = segments.size();
         Iterator<SelectedSegment> it = segments.iterator();
         int minAmount = Integer.MAX_VALUE;
         while(it.hasNext()){
         int current = it.next().getSegment().size();
         minAmount = (minAmount>current)?current:minAmount;
         }
        int j = 0;
        BigDecimal prom;
        while ((minAmount>j)) {
            prom = BigDecimal.ZERO;
            Iterator<SelectedSegment> itSegments = segments.iterator();
            while (itSegments.hasNext()) {
                SelectedSegment selectedSegment = itSegments.next();
                if ((selectedSegment.getSegment().size() > j)) {
                    prom = prom.add(selectedSegment.getSegment().elementAt(j));
                }
            }
            finalSegment.add(prom.divide(new BigDecimal(amountOfSements),MathUtils.CONTEXT));
            j++;
        }
        finalSegment = finalSegment.removeTrend();
        return finalSegment;
    }

    /**
     * @param segment
     * @param d
     * @return final segment derivatives 
     */
    public FinalSignal calcDerivatives(Segment segment, Derivative d) {

        FinalSignal finalSignal = d.derivate(segment);

        return finalSignal;
    }
}
